package com.reminis.exceldemo.config;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 日志配置类
 * 配置请求日志拦截器，记录所有HTTP请求的详细信息
 */
@Configuration
public class LoggingConfig implements WebMvcConfigurer {

    private static final Logger log = LogManager.getLogger(LoggingConfig.class);

    /**
     * 添加请求日志拦截器
     * @param registry 拦截器注册器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestLoggingInterceptor())
                .addPathPatterns("/api/**"); // 只拦截API请求
    }

    /**
     * HTTP请求日志拦截器
     * 记录每个HTTP请求的详细信息，包括请求参数、处理时间等
     */
    public static class RequestLoggingInterceptor implements HandlerInterceptor {

        private static final Logger requestLog = LogManager.getLogger("REQUEST_LOG");

        /**
         * 请求处理前的日志记录
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
            long startTime = System.currentTimeMillis();
            request.setAttribute("startTime", startTime);

            // 记录请求基本信息
            requestLog.info("=== HTTP请求开始 ===");
            requestLog.info("请求方法: {}", request.getMethod());
            requestLog.info("请求URL: {}", request.getRequestURL().toString());
            requestLog.info("请求URI: {}", request.getRequestURI());
            requestLog.info("客户端IP: {}", getClientIpAddress(request));
            requestLog.info("User-Agent: {}", request.getHeader("User-Agent"));
            
            // 记录请求参数
            if (request.getParameterMap() != null && !request.getParameterMap().isEmpty()) {
                requestLog.info("请求参数: {}", request.getParameterMap());
            }

            return true;
        }

        /**
         * 请求处理完成后的日志记录
         */
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                                   Object handler, Exception ex) {
            Long startTime = (Long) request.getAttribute("startTime");
            if (startTime != null) {
                long endTime = System.currentTimeMillis();
                long processingTime = endTime - startTime;

                requestLog.info("响应状态码: {}", response.getStatus());
                requestLog.info("处理耗时: {} ms", processingTime);
                
                if (ex != null) {
                    requestLog.error("请求处理异常: {}", ex.getMessage(), ex);
                }
                
                requestLog.info("=== HTTP请求结束 ===");
            }
        }

        /**
         * 获取客户端真实IP地址
         * @param request HTTP请求对象
         * @return 客户端IP地址
         */
        private String getClientIpAddress(HttpServletRequest request) {
            String xForwardedFor = request.getHeader("X-Forwarded-For");
            if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
                return xForwardedFor.split(",")[0].trim();
            }

            String xRealIp = request.getHeader("X-Real-IP");
            if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
                return xRealIp;
            }

            return request.getRemoteAddr();
        }
    }
}